﻿/*******************************************************************************
Copyright (c) 2011-2013, PKStudio

http://pkstudio.org

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*******************************************************************************/

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;

namespace PKEngine
{
	/// <summary>
	/// Singleton that handles the loading of surfaces.
	/// </summary>
	public class PKSurfaceCache
	{
		#region Private Fields
		private Dictionary<string, WeakReference> cachedSurfaces;
		#endregion

		#region Singleton
		private static PKSurfaceCache _sharedSurfaceCache;

		public static PKSurfaceCache SharedSurfaceCache
		{
			get
			{
				if (_sharedSurfaceCache == null)
				{
					_sharedSurfaceCache = new PKSurfaceCache();
				}
				return _sharedSurfaceCache;
			}
		}
		#endregion

		#region Initialization
		private PKSurfaceCache()
		{
			cachedSurfaces = new Dictionary<string, WeakReference>();
		}
		#endregion

		#region Public Methods
		/// <summary>
		/// Adds a image surface.
		/// </summary>
		/// <param name="filePath">The path of image file</param>
		/// <returns>Cached surface</returns>
		public PKSurface AddImage(string filePath)
		{
			Debug.Assert(!string.IsNullOrEmpty(filePath), "PKSurfaceCache.AddImage: Argument cannot be null.");
			Debug.Assert(File.Exists(filePath), "PKSurfaceCache.AddImage: Cannot find file.");

			string fileName = filePath.ToLower();
			PKSurface surface = GetSurface(fileName);
			if (surface == null)
			{
				string fileExt = Path.GetExtension(filePath).ToLower();
				switch (fileExt)
				{
					case ".png":
					case ".bmp":
					case ".gif":
					case ".jpg":
					case ".jepg":
						surface = new PKSurface(filePath);
						if (surface != null)
						{
							cachedSurfaces.Add(fileName, new WeakReference(surface));
						}
						break;
				}
			}

			return surface;
		}

		/// <summary>
		/// Gets a surface by key.
		/// </summary>
		/// <param name="key">The key</param>
		/// <returns>The surface</returns>
		public PKSurface GetSurface(string key)
		{
			if (cachedSurfaces.ContainsKey(key))
			{
				WeakReference pSurface = cachedSurfaces[key];
				if (!pSurface.IsAlive)
				{
					cachedSurfaces.Remove(key);
					return null;
				}
				else
				{
					return pSurface.Target as PKSurface;
				}
			}
			return null;
		}

		/// <summary>
		/// Removes a cached surface.
		/// </summary>
		/// <param name="surface">Target surface</param>
		public void RemoveSurface(PKSurface surface)
		{
			if (surface == null)
			{
				return;
			}

			foreach (KeyValuePair<string, WeakReference> kvPair in cachedSurfaces)
			{
				if (kvPair.Value.IsAlive && kvPair.Value.Target == surface)
				{
					cachedSurfaces.Remove(kvPair.Key);
					break;
				}
			}
		}

		/// <summary>
		/// Removes a cached surface.
		/// </summary>
		/// <param name="key">Target key</param>
		public void RemoveSurface(string key)
		{
			if (string.IsNullOrEmpty(key))
			{
				return;
			}

			cachedSurfaces.Remove(key);
		}

		/// <summary>
		/// Clears all unused surfaces.
		/// </summary>
		public void ClearUnusedSurfaces()
		{
			List<string> toRemoveList = new List<string>();
			foreach (KeyValuePair<string, WeakReference> kvPair in cachedSurfaces)
			{
				if (!kvPair.Value.IsAlive)
				{
					toRemoveList.Add(kvPair.Key);
				}
			}
			foreach (string key in toRemoveList)
			{
				cachedSurfaces.Remove(key);
			}
		}

		/// <summary>
		/// Clears all surfaces.
		/// </summary>
		public void ClearSurfaces()
		{
			cachedSurfaces.Clear();
		}
		#endregion
	}
}
